// pages/gettingWater/gettingWater.js
var app = getApp();
var paymeny = 0;
var conf_source = ''; //总后台配置来源
const {
    windowHeight,
    windowWidth
} = wx.getSystemInfoSync();


let serviceAxisX = Number.parseInt(windowWidth - 110 / 750 * windowWidth);
let serviceAxisY = Number.parseInt(windowHeight - 500 / 750 * windowWidth);
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 广告
        
        serviceAxisX,
        serviceAxisY,
        big: '../../images/8_l.png', //水量8L
        big_red: '../../images/8_r.png',
        content: '../../images/5_l.png', //水量5L
        content_red: '../../images/5_r.png',
        samll: '../../images/1_l.png', //水量1L
        samll_red: '../../images/1_r.png',
        waterType: '', //选择的打水量
        waterIndex: 0, //当前选中的打水下标
        waterKey: '', //当前选中的打水 key one two three
        waterAmountlst: [], //打水量列表
        watwerone: '',
        watwertwo: '',
        watwerthree: '',
        popupshow: false, //水卡弹窗
        selectShowcoupon: false, //优惠券弹窗
        equipment_sn: '', //设备编号
        pay_type: 3, //支付方式 2水卡 3微信支付 1积分支付
        actualMoney: 0, //实际支付金额
        needPay: {}, //应该支付的金额
        userinfo: {}, //用户信息
        cards: [],
        balance: "0.00",
        card_sn: "xxxx",
        card_id: 0,
        flag: true,
        have: '',
        rate: '', //兑换比例
        couponList: [],
        is_load: false,
        coupon_id: '',
        coupon_index: -1, //
        // cp_index: 0,//优惠券index
        // cose_idx: -1,//-1 不使用优惠券
        popshow: false, //联系客服
        serverMsg: {
            name: '',
            phone: '',
          integral_setting:''
        },
      outlet_list:'',//这个是打水出口配置
      cur_waterId:'',
      cur_waterIndex:0,
      contentHeight:'',
      outlet_id:'',
      is_waiting:true,//是否展示加载动画
    },

    /*** 生命周期函数--监听页面加载   此处代码没有改动sn*/
    onLoad: function (options) {
        console.log(this.data.serviceAxisX, "serviceAxisX");
        var sn;
        sn = options.equipment_sn ? options.equipment_sn : '861193047539284';

        if (options.q != undefined) {
            var scan_url = decodeURIComponent(options.q); //字符分割//console.log(scan_url); //打印出url//分割网址，提取出参数
            var surls = scan_url.split("equipment_sn=");
            var eid = surls[1];
            sn = eid ? eid : '';
        }
        var have = options.have ? options.have : ''; //判断是否需要返回按钮
        this.setData({
            equipment_sn: sn,
            have: have,
            cur_waterIndex:0
        });
        if (!this.data.equipment_sn || this.data.equipment_sn == '') {
            app.showModal('设备信息错误');
            return false;
        }
        this.getWaterConf();
        this.gitHeight();
    },
    //选择打水口
    choseType(e){
      var id = e.currentTarget.dataset.id, index = e.currentTarget.dataset.index;
      this.setData({ cur_waterId: id, cur_waterIndex:index,pay_type:3})//默认微信
      this.getWaterConf(id);
    },
  //切换整体swper
  bindchange(e) {
    var that = this;
    var cur_waterIndex = e.detail.current;
    this.setData({cur_waterIndex})
   var id= this.data.outlet_list[cur_waterIndex].id;
   this.setData({
    outlet_id:id,
    pay_type:3,//默认微信
   })  
     this.getWaterConf(id);
  },
  //获取屏幕高度
  gitHeight(){
    var that=this;
    wx.getSystemInfo({
      success: function (res) {
        console.log(res)
        that.setData({
          contentHeight: res.windowHeight-110
        })
       //WindowHeight = res.screenHeight;
      }
    })
  },
    //获取打水配置 获取合伙人电话号码
  getWaterConf(id='') {
        var that = this;
    that.setData({ is_waiting:true})
        app.ajax({
            url: "User/Equipment/getWaterConf",
            data: {
                "equipment_sn": that.data.equipment_sn,
                outlet_id:id
            },
            success: function (res) {
                var arr = [];
                var serverMsg = {
                    name: '',
                    phone: '',
                  integral_setting:''
                };
                serverMsg.name = res.data.data.partner.account_name;
                serverMsg.phone = res.data.data.partner.tel;
              serverMsg.integral_setting = res.data.data.partner.integral_setting;
                var newobj = res.data.data.conf;
                for (var item in newobj) {
                    newobj[item].id = item;
                    arr.push(newobj[item]);
                }
                // //console.log('处理之后的数据', arr)
                conf_source = res.data.data.source;
                var needPay = arr[0].predict_money;
                that.setData({
                    waterAmountlst: arr,
                    waterIndex: 0,
                    waterKey:arr[0].id,
                    needPay: needPay, //设置默认值
                    //actualMoney: arr[0].predict_money.water_card_pay, //设置默认值
                  watwerone: res.data.data.conf.one ? res.data.data.conf.one.rise:'',
                  watwertwo: res.data.data.conf.two ? res.data.data.conf.two.rise:'',
                  watwerthree: res.data.data.conf.three ? res.data.data.conf.three.rise:'',
                    serverMsg,
                    outlet_list: res.data.data.outlet_list,
                  is_waiting:false
                })
                that.calculationMoney(); //计算实际支付金额
                that.selectcoupon(0, false);
            }
        });
    },
    //返回首页
    backHome() {
        wx.redirectTo({
            url: '../home/home',
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
   onShow: function () {
      let that = this;
            wx.setStorageSync('is_first', true);
            this.getUser();
            this.setData({
                flag: true
            })
            var isBack = wx.getStorageSync('isBack') || false;
            //console.log('isBack', isBack);
            if (isBack) {
                //支付方式 2水卡 3微信支付 1积分支付
                if (this.data.pay_type != 1) {
                    this.selectcoupon(0, true);
                }
            }
            //掉接口
            that.getWaterConf();
        },

    /*** 生命周期函数--监听页面卸载*/
    onUnload: function () {
        wx.setStorageSync('isBack', false);
    },


    //计算金额金额
    calculationMoney(length) {
        var that = this;
        var payWay = that.data.pay_type;
        var coupon_index = that.data.coupon_index;
        var coupon_id = that.data.coupon_id;
        var couponList = that.data.couponList;
        var needPay = that.data.needPay;
        //console.log('0000', payWay)
        //支付方式 2水卡 3微信支付 1积分支付
        if (payWay == 1) {
            that.setData({
                actualMoney: that.data.needPay.integral_pay
            })
        } else if (payWay == 2 || payWay == 3) { //2水卡 3微信支付
            if (coupon_index == -1 || couponList.length <= 0) {
                that.setData({
                    actualMoney: payWay == 3 ? needPay.wx_pay : needPay.water_card_pay
                })
            } else {
              if (couponList[coupon_index].coupon_condition==1){
                var cuntNum = Number(couponList[coupon_index].coupon_condition_val.reduce) * 1000;
                var payMoney = payWay == 3 ? (Number(that.data.needPay.wx_pay * 1000) - cuntNum) / 1000 : (Number(that.data.needPay.water_card_pay * 1000) - cuntNum) / 1000;
              }
              if (couponList[coupon_index].coupon_condition == 2){
                var cuntNum = Number(couponList[coupon_index].coupon_condition_val.reduce);
                var payMoney = payWay == 3 ? Number(that.data.needPay.wx_pay * cuntNum)/100 : Number(that.data.needPay.water_card_pay * cuntNum)/100;
                
            }
                payMoney = Math.floor(payMoney * 100) / 100;
              if (payMoney<0){
                payMoney=0;
                }
                that.setData({
                    actualMoney: payMoney
                })
            }
        }
    },

    //选择打水量
    chooseType: function (e) {
        var that = this;
        var gitShow = e.currentTarget.dataset;
        if (gitShow.wtindex === that.data.waterIndex) {
            return false;
        }

        // //console.log('typev', gitShow);
        //积分或者是微信支付
        var needPay = that.data.waterAmountlst[gitShow.wtindex].predict_money;
        needPay.integral_pay = Number(needPay.integral_pay);
        if (that.data.pay_type == 1 && needPay.integral_pay > that.data.userinfo.integral) {
            that.setData({
                pay_type: 3
            })
        }
        console.log('切换的金额', needPay)
        this.setData({
            needPay: needPay,
            waterKey: gitShow.key,
            waterIndex: gitShow.wtindex,
            couponList: [],
            coupon_index: -1,
            coupon_id: ''
        })
        //支付方式 2水卡 3微信支付 1积分支付
        if (that.data.pay_type != 1) {
            this.selectcoupon(0, false);
        }
        this.calculationMoney(); //计算实际支付金额
    },
    // 单选支付方式按钮
    radioChange: function (e) {
        var that = this;
        var coupon_index = that.data.coupon_index;
        var couponList = that.data.couponList;
        var val = e.detail.value;
        var needPay = that.data.needPay;
        that.setData({
            pay_type: val,
        });
        if (val == 1) {
            that.setData({
                couponList: [],
                coupon_index: -1,
                coupon_id: '',
                actualMoney: needPay.integral_pay
            })
            coupon_index != -1 ? app.showToast('积分支付不能使用优惠券!') : '';
        } else {
            // that.selectcoupon(false);
            this.selectcoupon(0, false);
        }
        //2水卡 3微信支付 1积分支付



        //水卡支付 是否为空
        if (e.detail.value == '2') {
            if (that.data.cards.length <= 0) {
                wx.showModal({
                    title: '暂时没有水卡',
                    content: '是否申请?',
                    confirmColor: '#4EB7FF',
                    cancelColor: '#C4C4C4',
                    success: function (res) {
                        if (res.confirm) {
                            wx.navigateTo({
                                url: '../applyElectronicCard/applyElectronicCard',
                            })
                        } else if (res.cancel) {

                        }
                    }
                })
                return false;
            }
            that.setData({
                popupshow: true
            })
        }
    },
    //到申请水卡去
    chooseCardWay() {
        var that = this;
        if (that.data.cards.length <= 0) {
            wx.showModal({
                title: '暂时没有水卡',
                content: '是否申请? (水卡支付优惠更多)',
                confirmColor: '#FF6565',
                success: function (res) {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '../applyElectronicCard/applyElectronicCard',
                        })
                    } else if (res.cancel) {

                    }
                }
            })
            return false;
        }
        that.setData({
            popupshow: true
        })
    },
    //选择水卡
    radioChooseCrad: function (e) {
        var that = this;
        var card = that.data.cards;
        card.forEach(function (v, k) {
            if (v.water_id == e.detail.value) {
                that.setData({
                    balance: v.balance,
                    card_sn: v.card.substr(-4),
                })
            }
        })
        that.setData({
            card_id: e.detail.value,
        })
    },
    //取消关闭弹窗
    cancelBtn: function () {
        this.setData({
            popupshow: false
        })
        wx.setStorageSync('isBack', false);
    },
    //确认选择水卡
    affirmBtn: function (e) {
        this.setData({
            popupshow: false
        })
        wx.setStorageSync('isBack', false);
    },
    //获取用户信息
    getUser() {
        var that = this;
        app.ajax({
            url: "User/User/getUser",
            data: {},
            success: function (res) {
                if (res.data.code == 1000) {
                    var userinfo = res.data.data;
                    that.setData({
                        userinfo
                    });
                    that.getCards();
                } else {
                    wx.setStorageSync('token', '');
                    app.getToken();
                    // app.showModal('获取用户信息失败');
                }
            }
        })
    },
    //获取水卡信息
    getCards() {
        var that = this;
        app.ajax({
            url: "User/User/getWaterCard",
            data: {},
            success: function (res) {
                if (res.data.code == 1000) {
                    var getData = res.data.data;
                    if (getData.length > 1) {
                        getData.sort(function (a, b) {
                            return b.balance - a.balance;
                        });
                    }
                    var newArr = [];
                    getData.forEach((item, index) => {
                        item.cardCat = item.card.substr(-4);
                        item.balance = item.balance.slice(0, item.balance.length - 1)
                        newArr.push(item)
                    })
                    //console.log('newArr', newArr)
                    that.setData({
                        cards: newArr,
                    });
                    if (getData.length > 0) {
                        that.setData({
                            balance: newArr[0].balance,
                            card_sn: newArr[0].card.substr(-4),
                            card_id: newArr[0].water_id
                        });
                    }
                }
            }
        })
    },
    //选择优惠券
    chooseCoupon(e) {
        var index = e.currentTarget.dataset.index;
        var coupon_id = e.currentTarget.dataset.id;
        if (index == this.data.coupon_index) {
            this.setData({
                coupon_index: -1,
                coupon_id: ''
            })
        } else {
            this.setData({
                coupon_index: index,
                coupon_id
            })
        }
        this.calculationMoney(); //计算实际支付金额
    },
    //选择优惠券
    selectcoupon: function (e, isOpen = true) {
        var that = this;
        var open = e.currentTarget ? e.currentTarget.dataset.open : '';
        // console.log('e', e)
        var payWay = that.data.pay_type; //2水卡 3微信支付 1积分支付
        var findMoney = ''; //查询金额


        if (payWay == 1) {
            app.showToast('积分支付不能使用优惠券');
            return false;
        } else if (payWay == 2) {
            findMoney = that.data.needPay.water_card_pay
        } else if (payWay == 3) {
            findMoney = that.data.needPay.wx_pay
        }
        // console.log('外面', that.data.coupon_index,'这个payWay', payWay, '这个lg',that.data.couponList.length, '这个open',open)
        if (that.data.coupon_index != -1 && payWay != 1 && that.data.couponList.length > 0 && open == 1) {
            console.log('进来')
            that.setData({
                selectShowcoupon: true
            })
            return false
        }
        app.ajax({
            url: 'User/Coupon/selectCoupon',
            data: {
                money: findMoney
            },
            success: function (res) {
                if (res.data.code == 1000) {
                    that.setData({
                        couponList: res.data.data,
                        coupon_index: -1, //切换请求的时候置空选择
                    })
                } else {
                    that.setData({
                        couponList: [],
                        coupon_id: '',
                        coupon_index: -1, //切换请求的时候置空选择
                    })
                }
                that.setData({
                    is_load: true
                })
                isOpen ? that.setData({
                    selectShowcoupon: true
                }) : ''
                that.calculationMoney(); //计算实际支付金额
            }
        });
    },
    // 关闭选择优惠券弹窗
    closeSelectPop() {
        this.setData({
            selectShowcoupon: false
        })
    },
    //添加订单
    addOrder() {
        var that = this;
        if (!that.data.equipment_sn) {
            app.showToast('设备信息错误');
            return false;
        }

        // if (that.data.waterIndex) {
        //   app.showToast('请选择打水量'); return false;
        // }

        if (!that.data.pay_type) {
            app.showToast('请选择支付方式');
            return false;
        }
        // if (that.data.balance == 0 && that.data.pay_type!=1){
        //   app.showToast('余额不足,请换卡支付'); return false;
        // }
        if (that.data.pay_type == 2 && that.data.card_id == '') {
            if (that.data.cards.length <= 0) {
                wx.showModal({
                    title: '暂时没有水卡',
                    content: '是否申请?',
                    confirmColor: '#FF6565',
                    success: function (res) {
                        if (res.confirm) {
                            wx.navigateTo({
                                url: '../applyElectronicCard/applyElectronicCard',
                            })
                        } else if (res.cancel) {

                        }
                    }
                })
                return false;
            }
            app.showToast('请选择水卡');
            return false;
        }
        if (that.data.pay_type == 1 && that.data.coupon_id != '') {
            that.setData({
                coupon_id: '',
            });
            app.showToast('积分支付不能使用优惠券');
            return false;
        }

        if (!that.data.flag) {
            return false;
        }
        that.setData({
            flag: false
        })

        app.ajax({
            url: "User/Order/order",
            load: true,
            msg: '订单生成中...',
            data: {
                water_type: that.data.waterKey,
                equipment_number: that.data.equipment_sn,
                pay_type: that.data.pay_type,
                card_id: that.data.card_id,
                conf_source: conf_source,
                coupon_id: that.data.coupon_id,
                outlet_id:that.data.outlet_id
            },
            success: function (res) {
                if (res.data.code == 1000) {
                    var obj = res.data.data.order;
                    if (that.data.pay_type == 3 && res.data.data.is_wxpay == 1) {
                        //调起微信支付
                        wx.requestPayment({
                            timeStamp: obj.timeStamp,
                            nonceStr: obj.nonceStr,
                            package: obj.package,
                            signType: obj.signType,
                            paySign: obj.paySign,
                            success: function (res) {
                                that.pay_success();
                            },
                            fail: function (e) {
                                that.setData({
                                    flag: true
                                })
                                app.showToast('取消支付');
                            }
                        })
                    } else {
                        that.pay_success();
                    }
                } else {

                    app.showToast(res.data.message);
                    that.setData({
                        flag: true
                    })
                }

            }
        })
    },
    //支付成功跳转
    pay_success() {
        var that = this;
        app.showToast('支付成功', 'success');
        setTimeout(function () {
            wx.navigateTo({
                url: '../myOrderList/myOrderList?have=' + that.data.have
            })
        });
    },
    // 跳转领券中心
    goCoupon() {
        var that = this;
        wx.navigateTo({
            url: '../vouchercenter/vouchercenter?type=pay',
        })
    },
    none() {}, //不做处理
    //打开客服电话
    servicePop() {
        this.setData({
            popshow: !this.data.popshow
        })
    },
    //拨打电话
    cellServer(e) {
        var {
            phone
        } = e.currentTarget.dataset;

        wx.makePhoneCall({
            phoneNumber: phone
        })
    }
})